﻿using BlazorAdmin.Interface;
using BlazorAdmin.Models;
using Longbow.Tasks;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;

namespace Pangeo.Admin.Tasks
{
    /// <summary>
    /// 调度任务（基于IHostedService实现后台服务，不会在空闲时被系统挂起）
    /// </summary>
    public class HostedService : IHostedService
    {
        private readonly IJob jobService;
        private readonly SystemTask taskService;
        private readonly ILogger<HostedService> logger;

        public HostedService(IJob _jobService, SystemTask _taskService, ILogger<HostedService> _logger)
        {
            jobService = _jobService;
            taskService = _taskService;
            logger = _logger;
        }

        // 应用程序启动时，注册任务
        public async Task StartAsync(CancellationToken cancellationToken)
        {
            logger.LogInformation("Scheduled Service Is Starting");

            var jobs = await jobService.Query(JobStatus.Running);
            await taskService.CheckSystemTask(jobs);
            Console.WriteLine($"task: {string.Join("、", jobs.Select(t => t.JobCode))} Is Running !");
            Console.WriteLine("--------------------------------------------------------------------");
        }

        // 应用程序停止时，清理资源
        public Task StopAsync(CancellationToken cancellationToken)
        {
            logger.LogInformation("Scheduled Service Is Stopping");

            // 清除所有调度任务
            TaskServicesManager.Clear();

            return Task.CompletedTask;
        }
    }
}
